/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.pvacameras.server;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.google.pvacameras.server.config.Config;
import com.google.wallet.online.jwt.MaskedWalletRequest;
import com.google.wallet.online.jwt.Pay;
import com.google.wallet.online.jwt.Ship;
import com.google.wallet.online.jwt.WalletBody;
import com.google.wallet.online.jwt.util.WalletOnlineService;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.MethodInvocationException;

/**
 * Order Page Servlet that renders the order detail page and generates the
 * MaskedWalletRequest.
 * 
 * Templating uses Velocity Template
 * 
 * 
 * @author David Peng (gpeng@google.com)
 * 
 */

public class OrderServlet extends HttpServlet {

	private static final long serialVersionUID = -4919105809489724586L;

	/**
	 * Get handler forwards request to post handler
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException {
		doPost(req, resp);
	}

	/**
	 * Post handler renders the template generates the maskedWalletRequest and
	 * injects the JWT into the template
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse resp) {
		try {
			String origin = Config.getDomain(req);
			// Get post parameters
			String name = req.getParameter("itemName");
			String unitprice = req.getParameter("itemPrice");
			String quantity = req.getParameter("itemQuantity");
			String image = req.getParameter("itemImage");
			String description = req.getParameter("itemDescription");
			// Create the WalletBody for the maskedWalletRequest
			WalletBody mwb = new WalletBody(Config.OAUTH_CLIENT_ID,
					Config.MERCHANT_NAME, origin, new Pay(unitprice, "USD"), new Ship());
			mwb.setPhoneNumberRequired(true);

			// Create the maskedWalletRequest object using the WalletBody
			MaskedWalletRequest mwr = new MaskedWalletRequest(mwb);

			// Apply the utility service for conversion between Wallet Java objects
			// and JWT
			WalletOnlineService ows = new WalletOnlineService(Config.getMerchantId(),
					Config.getMerchantSecret());

			// So we don't write to velocity.log
			Velocity.setProperty("runtime.log.logsystem.class",
					"org.apache.velocity.runtime.log.NullLogChute");

			// Escape HTML
			Velocity.setProperty("eventhandler.referenceinsertion.class",
					"org.apache.velocity.app.event.implement.EscapeHtmlReference");
			Velocity.setProperty("eventhandler.escape.html.match", "/.*/");

			// Initialize Velocity Templates
			Velocity.init();
			VelocityContext context = new VelocityContext();

			// Get the response output stream PrintWriter
			PrintWriter pw;
			pw = resp.getWriter();

			// Injects the JWT into the template
			context.put("mwr", ows.javaToJwt(mwr));
			context.put("itemName", name);
			context.put("itemPrice", unitprice);
			context.put("itemQuantity", quantity);
			context.put("itemImage", image);
			context.put("itemDescription", description);
			context.put("totalPrice", Integer.parseInt(unitprice)+9.99+8);
			// Get the response output stream PrintWriter

			// Render the template and output to print stream
			Velocity.mergeTemplate("order.vm", "UTF-8", context, pw);
			pw.flush();
			pw.close();
		} catch (ResourceNotFoundException e) {
			e.printStackTrace();
		} catch (ParseErrorException e) {
			e.printStackTrace();
		} catch (MethodInvocationException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
